//
//  MZTimeTableSegmentedViewController.m
//  Mehfile Zainab
//
//  Created by Sitara Badourali on 14/06/12.
//  Copyright (c) 2012 Mehfile Zainab. All rights reserved.
//

#import "MZTimeTableSegmentedViewController.h"
#import "TimeTableXMLParser.h"
#import "MZTimeTable.h"
#import "MZInfosViewController.h"

@implementation MZTimeTableSegmentedViewController

@synthesize groupedTableView;
@synthesize segmentedControl;
@synthesize spinner;
@synthesize alertView;
@synthesize mzTimeTableArray;


/*
- (void)showInfo:(id)sender
{
    NSLog(@"Info button tapped, show modal view");
    MZInfosViewController *mzInfosViewController = [[MZInfosViewController alloc]
                                                    initWithNibName:@"MZInfosViewController" bundle:nil];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:mzInfosViewController];
    mzInfosViewController.title = @"Informations";
    [mzInfosViewController release];
	navController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]
									  initWithTitle:@"Fermer"
									  style:UIBarButtonItemStyleBordered
									  target:mzInfosViewController
									  action:@selector(GoBack:)];
	mzInfosViewController.navigationItem.leftBarButtonItem = barButtonItem;
    [self.tabBarController presentModalViewController:navController animated:YES];
    [navController release];
    
}
 */

/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //self.title = NSLocalizedString(@"Second", @"Second");
        self.tabBarItem.image = [UIImage imageNamed:@"namaz_icon"];
    }
    return self;
}
*/

- (void)parseXMLFile {
    
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    // get the current date
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormat = [[[NSDateFormatter alloc]init] autorelease];
    [dateFormat setDateFormat:@"MMMM"];
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    NSString *currentMonth = [[dateFormat stringFromDate:today] lowercaseString];
    
    NSLog(@"Init the XML parsing with file corresponding to month : %@",currentMonth);
   	NSString *bundle = [[NSBundle mainBundle] pathForResource:currentMonth ofType:@"xml"];
    //NSString *bundle = [[NSBundle mainBundle] pathForResource:@"June" ofType:@"xml"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:bundle];
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
    
    //Initialize the delegate.
    TimeTableXMLParser *parser = [[TimeTableXMLParser alloc] initXMLParser:self queriedDate:today];
    
    //Set delegate
    [xmlParser setDelegate:parser];
    
    //Start parsing the XML file.
    BOOL success = [xmlParser parse];
    
    if(success)
        NSLog(@"No Errors");
    else
        NSLog(@"Error when parsing XML file!");
    
    [self parseAgainXMLFile];
    
    [self stopLoading];
    
    [pool drain];
    
}

- (void)parseAgainXMLFile {
    
    //NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    // get the next date
    NSDate *tomorrow = [NSDate dateWithTimeInterval:(24*60*60) sinceDate:[NSDate date]];
    
    NSDateFormatter *dateFormat = [[[NSDateFormatter alloc]init] autorelease];
    [dateFormat setDateFormat:@"MMMM"];
    [dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    NSString *currentMonth = [[dateFormat stringFromDate:tomorrow] lowercaseString];
    
    NSLog(@"Init the XML parsing with file corresponding to month : %@",currentMonth);
   	NSString *bundle = [[NSBundle mainBundle] pathForResource:currentMonth ofType:@"xml"];
    //NSString *bundle = [[NSBundle mainBundle] pathForResource:@"June" ofType:@"xml"];
    NSData *data = [[NSData alloc] initWithContentsOfFile:bundle];
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:data];
    
    //Initialize the delegate.
    TimeTableXMLParser *parser = [[TimeTableXMLParser alloc] initXMLParser:self queriedDate:tomorrow];
    
    //Set delegate
    [xmlParser setDelegate:parser];
    
    //Start parsing the XML file.
    BOOL success = [xmlParser parse];
    
    if(success)
        NSLog(@"No Errors");
    else
        NSLog(@"Error when parsing XML file!");
    
    //[pool drain];
    
}

-(void) startLoading:(id)data  {
	
	//NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
	[spinner setCenter:CGPointMake(140, 100)]; 
	
	NSString* messageTitleToUser = @"Mehfile Zainab"; 
	alertView = 
    [[UIAlertView alloc]	initWithTitle:messageTitleToUser 
                               message:@"Chargement..." 
                              delegate:self 
                     cancelButtonTitle:nil
                     otherButtonTitles:nil];
	
	[alertView addSubview:spinner];
	[spinner startAnimating];
	[alertView show]; 
	
	//[pool drain];
	
}

-(void) stopLoading  {
	//if you programmatically want to close the alert view 
	[alertView dismissWithClickedButtonIndex:0 animated:YES];
	// stop spinner 
	[spinner stopAnimating];
    
    [self.groupedTableView reloadData];
    
}


- (void)initTimeTable {
    
    [self startLoading:nil];
    
    //[self performSelectorOnMainThread:@selector(startLoading:) withObject:nil waitUntilDone:YES];
	
	//[NSThread detachNewThreadSelector:@selector(startLoading:) toTarget:self withObject:nil];
    
    [NSThread detachNewThreadSelector:@selector(parseXMLFile) toTarget:self withObject:nil];
    
    //[self parseXMLFile];

    //[self parseAgainXMLFile];
    
    //[self stopLoading];
    
    /*
     mzTimeTableArray = [[NSMutableArray alloc] init];
     MZTimeTable *timeTable;
     NSMutableArray *timeValues;
     
     timeTable = [[MZTimeTable alloc] init];
     timeValues = [[NSMutableArray alloc] init];
     [timeValues addObject:@"01h00"];
     [timeValues addObject:@"02h00"];
     [timeValues addObject:@"03h00"];
     [timeValues addObject:@"04h00"];
     [timeValues addObject:@"05h00"];
     timeTable.mzNamazDate = @"17 Avril 2012";
     [timeTable setNamazTimeDictionaryWithValuesArray:timeValues];
     
     [mzTimeTableArray addObject:timeTable];
     [timeValues release];
     [timeTable release];
     
     timeTable = [[MZTimeTable alloc] init];
     timeValues = [[NSMutableArray alloc] init];
     [timeValues addObject:@"06h00"];
     [timeValues addObject:@"07h00"];
     [timeValues addObject:@"08h00"];
     [timeValues addObject:@"09h00"];
     [timeValues addObject:@"10h00"];
     timeTable.mzNamazDate = @"18 Avril 2012";
     [timeTable setNamazTimeDictionaryWithValuesArray:timeValues];
     [mzTimeTableArray addObject:timeTable];
     [timeValues release];
     [timeTable release];
     */
    
}


-(IBAction) segmentedControlIndexChanged {
    switch (self.segmentedControl.selectedSegmentIndex) {
        case 0:
            //testString = @"Today";
            pointer = 0;
            break;
        case 1:
            //testString = @"Tomorrow";
            pointer = 1;
            break;
        default:
            break;
    }
    [self.groupedTableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
	return 1;
	//return [mzTimeTableArray count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	//return 1;
	//return [[[mzTimeTableArray objectAtIndex:section] getNamazDefinitionArray] count];
    if ((mzTimeTableArray==nil) || ([mzTimeTableArray count]==0)) return 0;
    return [[[mzTimeTableArray objectAtIndex:pointer] getNamazDefinitionArray] count];
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	//return @"Title test";
	//return [[mzTimeTableArray objectAtIndex:section] getNamazDate];
    if ((mzTimeTableArray==nil) || ([mzTimeTableArray count]==0)) return 0;
    return [[mzTimeTableArray objectAtIndex:pointer] getNamazDate];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return nil;
    }
	
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(20, 8, 320, 20);
    label.backgroundColor = [UIColor clearColor];
    label.text = sectionTitle;
	label.textColor = [self colorFromHexString:@"#C22809"];
    label.font = [UIFont fontWithName:@"Futura-CondensedMedium" size:25.0f];
	
    UIView *view = [[UIView alloc] init];
    [view addSubview:label];
	
    return view;
}

- (UIColor *)colorFromHexString:(NSString *)hexString {
    unsigned rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    [scanner setScanLocation:1]; // bypass '#' character
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
}

/*
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	return 28.0f;
	
}
*/

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    //[cell.textLabel setText:testString];
    if ((mzTimeTableArray==nil) || ([mzTimeTableArray count]==0)) return cell;
    
    /*
    NSString *namazName = [[[mzTimeTableArray objectAtIndex:indexPath.section] getNamazDefinitionArray] objectAtIndex:indexPath.row];
	NSString *namazTime = [[[mzTimeTableArray objectAtIndex:indexPath.section] getNamazTimeDictionary] objectForKey:namazName];
	*/
    NSString *namazName = [[[mzTimeTableArray objectAtIndex:pointer] getNamazDefinitionArray] objectAtIndex:indexPath.row];
	NSString *namazTime = [[[mzTimeTableArray objectAtIndex:pointer] getNamazTimeDictionary] objectForKey:namazName];
    
    // Configure the cell...
	
	cell.textLabel.textColor = [self colorFromHexString:@"#045905"];
    cell.textLabel.font = [UIFont fontWithName:@"Futura-CondensedMedium" size:25.0f];
    [cell.textLabel setText:namazTime];
	
	cell.detailTextLabel.textColor = [self colorFromHexString:@"#bcc2c8"];
    cell.detailTextLabel.font = [UIFont fontWithName:@"Futura-CondensedMedium" size:25.0f];
    [cell.detailTextLabel setText:namazName];
	
	[cell setUserInteractionEnabled:NO];
	
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    // Navigation logic may go here. Create and push another view controller.
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
}

/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
*/

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    // Do any additional setup after loading the view from its nib.
	
    //self.navigationController.navigationBar.translucent = NO;
    
    //testString = @"Init to Today";
    
	[self initTimeTable];
    
    [self.segmentedControl setWidth:100 forSegmentAtIndex:0];
    [self.segmentedControl setWidth:100 forSegmentAtIndex:1];
    CGRect rectFrame = CGRectMake(60,0,200,30);
    [self.segmentedControl setFrame:rectFrame];
    
    pointer = 0;
}

-(void)viewWillDisappear:(BOOL)animated
{
    NSLog(@"View will disappear, set again navigation bar to translucent");
    //self.navigationController.navigationBar.translucent = YES;
    [super viewWillDisappear:animated];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
